package com.itcast.donkey.fragments;


import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.itcast.donkey.R;
import com.itcast.donkey.adapters.FigureAdapter;
import com.itcast.donkey.adapters.TravelItemAdapter;
import com.itcast.donkey.modles.TravelFigureModels;
import com.itcast.donkey.modles.TravelItemModels;
import com.itcast.donkey.modles.UriModles;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;

import org.json.JSONArray;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lanouhn on 16/8/23.
 */
public class TravelFragment extends Fragment {
    private XRecyclerView xRecyclerView;
    private TravelItemAdapter adapter;
    //轮播图设置
    private ArrayList<TravelFigureModels> travelFigureModelsList = new ArrayList<>();
    private FigureAdapter figureAdapter;
    private RollPagerView rollPagerView;


    //上拉加载和下拉刷新
    private int page = 1;
    //真实值
    private ArrayList<TravelItemModels> travelItemModelsList = new ArrayList<>();
    //中间值
    private ArrayList<TravelItemModels> temptravelItemModelsList = new ArrayList<>();




    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_travel, null);
        //下拉刷新和上拉加载
        xRecyclerView = (XRecyclerView) view.findViewById(R.id.xRecyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        xRecyclerView.setLayoutManager(layoutManager);


        //上拉加载的动画效果
        xRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        //recyclerView.setLaodingMoreProgressStyle(ProgressStyle.Pacman);
        //下拉刷新的动画效果
        xRecyclerView.setArrowImageView(R.drawable.ic_loading_rotate);

        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            //下拉刷新
            @Override
            public void onRefresh() {
                page = 1;
                initItemData();
            }

            //上拉加载
            @Override
            public void onLoadMore() {
                page++;
                initItemData();
            }
        });
        rollPagerView = new RollPagerView(getActivity());
        rollPagerView.setPlayDelay(3000);
        rollPagerView.setAnimationDurtion(500);

        LinearLayout.LayoutParams imagefigure = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 400);
        imagefigure.setMargins(20, 30, 20, 5);
        rollPagerView.setLayoutParams(imagefigure);
        rollPagerView.setHintView(new ColorPointHintView(getActivity(), Color.YELLOW, Color.WHITE));

        xRecyclerView.addHeaderView(rollPagerView);


        initItemData();
        initFigureData();

        return view;
    }


    private void initItemData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String p = Integer.toString(page);
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(UriModles.TRAVEL_ITEM_URL + p)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
//                        handler.sendEmptyMessage(0);
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();

                        Gson gson = new Gson();
                        try {
                            JSONArray jsonArray = new JSONArray(result);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                TravelItemModels item = gson.fromJson(jsonArray.get(i).toString(), TravelItemModels.class);
                                temptravelItemModelsList.add(item);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (temptravelItemModelsList.size() > 0) {
                            handler.sendEmptyMessage(1);
                        } else {
                            handler.sendEmptyMessage(0);
                        }
                    }
                });

            }
        }).start();
    }

    public void initFigureData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient clientFigure = new OkHttpClient();
                final Request requestFigure = new Request.Builder()
                        .url(UriModles.TRAVEL_FIGURE_URL)
                        .build();
                Call callFigure = clientFigure.newCall(requestFigure);
                callFigure.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String resultFigure = response.body().string();

                        try {
                            travelFigureModelsList = new ArrayList<>();
                            JSONArray array = new JSONArray(resultFigure);
                            Gson gsonFigure = new Gson();
                            for (int i = 0; i < array.length(); i++) {
                                TravelFigureModels t = gsonFigure.fromJson(array.get(i).toString(), TravelFigureModels.class);
                                travelFigureModelsList.add(t);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (travelFigureModelsList.size() > 0) {
                            handler.sendEmptyMessage(2);
                        } else {
                            handler.sendEmptyMessage(3);
                        }
                    }
                });
            }
        }).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(getActivity(), "解析失败0", Toast.LENGTH_SHORT).show();
                    xRecyclerView.refreshComplete();
                    xRecyclerView.loadMoreComplete();
                    break;
                case 1:
                    if (page == 1) {
                        travelItemModelsList.clear();
                        travelItemModelsList.addAll(temptravelItemModelsList);
                        //获取适配器
                        adapter = new TravelItemAdapter(getActivity(), travelItemModelsList);
                        //绑定适配器
                        xRecyclerView.setAdapter(adapter);

                        xRecyclerView.refreshComplete();
                        temptravelItemModelsList.clear();
                    } else {
                        travelItemModelsList.addAll(temptravelItemModelsList);
                        adapter.notifyDataSetChanged();
                        xRecyclerView.loadMoreComplete();
                        temptravelItemModelsList.clear();
                    }
                    break;
                case 2:
                    figureAdapter = new FigureAdapter(getActivity(), travelFigureModelsList);
                    rollPagerView.setAdapter(figureAdapter);
                    break;
                case 3:
                    Toast.makeText(getActivity(), "解析失败3", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
}
